package com.ytjj.qmyx.mall.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.ytjj.qmyx.mall.config.MyWxConfig;
import com.ytjj.qmyx.mall.constants.CompanyConstant;
import com.ytjj.qmyx.mall.mapper.OrdersDao;
import com.ytjj.qmyx.mall.model.PayConfig;
import com.ytjj.qmyx.mall.service.WxTransferService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * 商户提现到用户余额
 *
 *
 *  *
 **/
@Service
@Slf4j
public class WxTransferServiceImpl implements WxTransferService {

    @Resource
    private OrdersDao ordersDao;



    public static final String TYPE = "APP";

    public static final String TRADE_TYPE = "APP";

    //文档 https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_1

    @Override
    public boolean transfer(String partnerTradeNo, String openid, String amount, String desc) throws Exception {

        PayConfig payConfig = ordersDao.getPayConfigByCompany(CompanyConstant.PLATFORM, TYPE, TRADE_TYPE);
        log.info("===payConfig==={}", payConfig);
        MyWxConfig myWxConfig = new MyWxConfig(payConfig);
        WXPay wxpay = new WXPay(myWxConfig, WXPayConstants.SignType.MD5);
        log.info("===myWxConfig==={}", myWxConfig);

        Map<String, String> data = new HashMap<>();
        data.put("mch_appid", payConfig.getAppid()); //商户账号appid
        data.put("mchid", payConfig.getMchId());     //商户号
        data.put("nonce_str", WXPayUtil.generateNonceStr());
        data.put("partner_trade_no", partnerTradeNo);//商户订单号，需保持唯一性
        data.put("openid", openid);                  //商户appid下，某用户的openid
        data.put("check_name", "NO_CHECK");          //NO_CHECK：不校验真实姓名
        data.put("amount", amount);                  //单位为分
        data.put("desc", desc);                      //备注
        data.put("sign", WXPayUtil.generateSignature(data, payConfig.getWxKey(),
                WXPayConstants.SignType.MD5));      //签名


        log.info("微信转账请求123 param: {}", JSONObject.toJSONString(data));
        String respXml = wxpay.requestWithCert("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers", data, 1000, 1000);
        log.info("===微信转账响应==={}", respXml);
        Map<String, String> respData = WXPayUtil.xmlToMap(respXml);
//        Map<String, String> response = wxpay.processResponseXml(respXml);
        if ("SUCCESS".equals(respData.get("return_code"))) {
            if(!"SUCCESS".equals(respData.get("result_code"))){
                String errCode = respData.get("err_code");
                if(errCode.equals("SYSTEMERROR")) {
                    Map<String, String> transferInfo = getTransferInfo(wxpay, partnerTradeNo);
                    if("SUCCESS".equals(transferInfo.get("return_code")) && "SUCCESS".equals(transferInfo.get("result_code")) && "SUCCESS".equals(transferInfo.get("status"))) {
                        //成功
                        return true;
                    }
                }
                //失败
                return false;
            }
            //成功
            return true;
        }
        return false;
    }

    /**
     * 查询 企业付款
     *
     */
    public Map<String, String> getTransferInfo(WXPay wxpay,String partnerTradeNo) throws Exception {
        Map<String, String> data = new HashMap<>();
        data.put("partner_trade_no", partnerTradeNo);          //商户订单号，需保持唯一性
        String respXml = wxpay.requestWithoutCert("https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo", wxpay.fillRequestData(data), 1000, 1000);
        Map<String, String> response = wxpay.processResponseXml(respXml);
        return response;
    }


    public static void main(String[] args) throws Exception {
        PayConfig payConfig = new PayConfig();
        payConfig.setAppid("wx1e01bd6333a8089a");
        payConfig.setMchId("1514386431");
        payConfig.setWxKey("P7975F4F3CB5ABWF9A2FED4D0M2663L4");
        payConfig.setCertPath("E:\\pay_cert\\apiclient_cert.p12");
        MyWxConfig myWxConfig = new MyWxConfig(payConfig);

        Map<String, String> data = new HashMap<>();
        WXPay wxpay = new WXPay(myWxConfig, WXPayConstants.SignType.MD5);

        data.put("mch_appid", payConfig.getAppid()); //商户账号appid
        data.put("mchid", payConfig.getMchId());     //商户号
        data.put("nonce_str", WXPayUtil.generateNonceStr());
        data.put("partner_trade_no", "Y202106281119515850348");//商户订单号，需保持唯一性
        data.put("openid", "oBVI552MRgijLtHDwaPCSnfcbeMc");                  //商户appid下，某用户的openid
        data.put("check_name", "NO_CHECK");          //NO_CHECK：不校验真实姓名
        data.put("amount", "13800");                  //单位为分
        data.put("desc", "测试");                      //备注
        data.put("sign", WXPayUtil.generateSignature(data, payConfig.getWxKey(),
                WXPayConstants.SignType.MD5));      //签名

        log.info("微信H5支付状态查询请求 订单号：{},query: {}", "PAY202101101757230885756", JSONObject.toJSONString(data));
        //使用官方API请求预付订单
        String response = wxpay.requestWithCert("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers", data, 1000, 1000);
        log.info("微信H5支付状态查询响应 订单号：{},response: {}", "PAY202101101757230885756", JSONObject.toJSONString(response));


    }

}
